package ru.arriah.servicedesk.web.client;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.bean.MessageBean;
import ru.arriah.common.web.UIController;
import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;

public class ClientUI extends UIController {
   protected ClientManagerLocalHome clientManagerHome;
   
   public ClientUI() {
      super();
   }
   
   
   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      try {
         clientManagerHome =
            (ClientManagerLocalHome) (new InitialContext()).lookup(
               "java:comp/env/ejb/ClientManager"
            );
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   
   protected void prologue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {

     Object userId = Utils.getUserId(request);

      if (
         userId == null && !actionMapping.getActionName().equals("login")
      ) {
         request.getSession().setAttribute("alias", "clientui");
         throw new LoginException("ErrorMessage.relogin");
      }

      String uri = request.getRequestURI();
      String query = request.getQueryString();

      if (query != null) {
         uri += "?" + query;
      }

      String uriEncoded = URLEncoder.encode(uri, "UTF-8");
      request.setAttribute("uri", uri);
      request.setAttribute("uriEncoded", uriEncoded);
      
      //messages list
      request.setAttribute(
         "messagesList", 
         new ArrayList<MessageBean>()
      );
            
   }   
   

   protected void epilogue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {
         Object userId = Utils.getUserId(request);
         
         ClientManagerLocalObject clientManager = clientManagerHome.create();
         ClientBean clientBean = clientManager.selectClient((Integer)userId);
         clientManager.remove();
         request.setAttribute("clientName", clientBean.getFormName());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}